/* SPI Master example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_log.h"
#include "esp_wifi.h"
#include "nvs_flash.h"

#include "captive_portal.h"
#include "pretty_effect.h"
#include "app_sntp.h"
#include "file_manage.h"
#include "file_server.h"
#include "decode_image.h"

#include "epd2in13.h"
#include "epdpaint.h"
#include "board.h"
#include "app_show_image.h"
#include "show_text.h"
#include "mp3_player.h"
#include "dht11.h"

static const char *TAG = "Eink";
//#define WIFI_IN_HOME    1

uint8_t hssid[]="openwrt";
uint8_t hpass[]="qwertyuiop";

bool show_mode_img =1;
float tem=0.0,hum=0.0;
uint8_t update_draw_flag=0;
/**
  * Due to RAM not enough in Arduino UNO, a frame buffer is not allowed.
  * In this case, a smaller image buffer is allocated and you have to
  * update a partial display several times.
  * 1 byte = 8 pixels, therefore you have to set 8*N pixels at a time.
  */
static unsigned char image[EPD_WIDTH * EPD_HEIGHT / 8];

#include "Ap_29demo.h"

void app_main(void)
{
    board_init();
    ESP_LOGI(TAG, "------------ system start ------------");
    //Initialize NVS
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) 
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    //
//    nvs_flash_erase();
    //check usb & charge.
    ESP_LOGI(TAG,"usb connect state:%s,charge:%s\n",board_usb_check()?"yes":"no",board_charge_check()?"yes":"no");
    ESP_LOGI(TAG,"btn1 on/off state:%s\n",board_on_off_check()?"yes":"no");
//  while(1)
    {
        Epd_Init(EPD_2IN13_FULL);
        ESP_LOGI(TAG, "Epd init.");
        Epd_Clear();
        ESP_LOGI(TAG, "Epd clear.");

        //Epd_Draw_Grid();
        //ESP_LOGI(TAG, "Draw grid.");
       // while(1);
        //Epd_Clear();
    }
/*    ESP_LOGI(TAG, "display good good study!");
    Paint_init(image, EPD_WIDTH, EPD_HEIGHT);
    Paint_Clear(UNCOLORED);
    Paint_SetRotate(ROTATE_90);
    Epd_draw_bitmap(0, 0, 104, 212, gImage_ggsd);
    Epd_DisplayFrame();
    Epd_DeepSleep();
  */
    // vTaskDelete(NULL);
    Epd_Init(EPD_2IN13_FULL);
    Paint_init(image, EPD_WIDTH, EPD_HEIGHT);
    Paint_SetRotate(ROTATE_90);
    Paint_Clear(UNCOLORED);
    Paint_DrawStringAt(0, 0, "start", &Font16, COLORED);
    Epd_draw_bitmap(0, 0, EPD_WIDTH, EPD_HEIGHT, Paint_GetImage());

    Epd_DisplayFrame();

    printf("start config wifi.\n");
    bool is_configured;
    char str_buf[128] = {0};
    captive_portal_start("ESP_CONFIG", NULL, &is_configured);
    wifi_config_t wifi_config;
    esp_wifi_get_config(ESP_IF_WIFI_STA, &wifi_config);
#ifdef WIFI_IN_HOME
//change ssid\passwd
    strcpy((char *)wifi_config.sta.ssid,(char *)hssid);
    strcpy((char *)wifi_config.sta.password,(char *)hpass);
    
#endif
    if (is_configured) {
        sprintf(str_buf, "SSID:%s, PASSWORD:%s", wifi_config.sta.ssid, wifi_config.sta.password);
        printf("%s\n",str_buf);
        Paint_DrawStringAt(0, 16, str_buf, &Font12, COLORED);
    } else {
        sprintf(str_buf, "WiFi not configured, started a configuration webpage");
         printf("%s\n",str_buf);

        Paint_DrawStringAt(0, 32, str_buf, &Font12, COLORED);
    }
    Epd_Init(EPD_2IN13_FULL);
    Epd_draw_bitmap(0, 0, EPD_WIDTH, EPD_HEIGHT, Paint_GetImage());
    Epd_DisplayFrame();
    Epd_DeepSleep();

    captive_portal_wait(portMAX_DELAY);
    sntp_start();
    ESP_ERROR_CHECK(fm_init());
    /* Initialize file storage */
    
    start_file_server();

   //mp3
   //board_pa_ctrl(true);
    //board_pa_ctrl(false);

    time_t now;
    struct tm timeinfo;
    char strftime_buf[64];

    app_show_text_init();

//    ESP_LOGI(TAG, "Redy  to print text.");
//    
    /*
    Paint_Clear(UNCOLORED);
    Epd_Init(EPD_2IN13_FULL);
    app_show_text_str(0, 0, 200, 100, "现在的时间是:", 16, 1);
    Epd_draw_bitmap(0, 0, EPD_WIDTH, EPD_HEIGHT, Paint_GetImage());
    Epd_DisplayFrame();
    Epd_DeepSleep();
    */
//    image_show_start();
    uint8_t epd_update_mode = EPD_2IN13_FULL;
    float temp=0.0,humi=0.0;
    uint8_t retval;
    ESP_LOGI(TAG, "Enter loop..");

    char time_buf[30];
    char date_buf[30];
    char year_buf[14];
    char env_buf[30];
    char flash_cnt=0;
    while (1) {

	    //check on/off btn1
	    printf("key btn1 on/off state:%d\n", board_on_off_check());
	    retval = DHT11_GetResult(&temp,&humi);
	    ESP_LOGI(TAG,"temp:%.02f,humi:%.02f",temp,humi);
        if(!retval&&(temp-tem > 0.2 || tem-temp > 0.2 || humi - hum >0.5 || hum - humi > 0.5)){
            tem = temp;
            hum = humi;
            update_draw_flag=1;
        }
        time(&now);
        localtime_r(&now, &timeinfo);
        strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
        
        sprintf(time_buf," %02d:%02d:%02d ",timeinfo.tm_hour,timeinfo.tm_min,timeinfo.tm_sec);
        sprintf(date_buf,"%02d月%02d日 ",timeinfo.tm_mon+1,timeinfo.tm_mday);
        sprintf(year_buf," %d ",timeinfo.tm_year+1900);
        sprintf(env_buf,"温度:%2.1f,湿度:%2.1f%%",tem,hum);
        ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);

        Paint_Clear(UNCOLORED);
        if(flash_cnt>60||flash_cnt == 0 || update_draw_flag) 
        {
                flash_cnt =1;
                update_draw_flag=0;
                Epd_Init(EPD_2IN13_FULL);
        }
        else{

                flash_cnt++;
                 Epd_Init(EPD_2IN13_PART);
        }

        app_show_text_str(0, 0, 200, 100, "现在的时间是:", 16, 1);
        app_show_text_str(70,20,200,100,time_buf,16,1);

        app_show_text_str(40,35,200,100,year_buf,16,1);
        app_show_text_str(40+strlen(year_buf)*8,32,200,100,"年",16,1);

        app_show_text_str(40+strlen(year_buf)*8 + 2*8,35,200,100,date_buf,16,1);

        app_show_text_str(40,50,200,100,env_buf,16,1);
        //app_show_text_str(0,50,200,100,strftime_buf,16,1);
        Epd_draw_bitmap(0,0,EPD_WIDTH,EPD_HEIGHT,Paint_GetImage());
        Epd_DisplayFrame();
        Epd_DeepSleep();
        
        /*if(!show_mode_img){
            Epd_Init(epd_update_mode);
    //      Epd_SetFrameMemory_Area( 0, 0, EPD_WIDTH, EPD_HEIGHT);
            Epd_draw_bitmap(0, 0, EPD_WIDTH, EPD_HEIGHT, Paint_GetImage());
            Epd_DisplayFrame();
    	    Epd_DeepSleep();
            epd_update_mode = EPD_2IN13_PART;
       }else{
            epd_update_mode = EPD_2IN13_FULL;
       
       }

       */
        vTaskDelay(pdMS_TO_TICKS(10*1000));
    }
}

